package databaseHelper;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import datatypes.Exam;
import datatypes.User;

/**
 * 
 * Data Access Object that provides infos to many
 * 
 * @author Rupert
 *
 */
public class UserDAO {
	
	DataSource ds = DataSource.INSTANCE;

	
	public int verifyLogin(User loginUser) throws SQLException {
					
		String query = 	"SELECT id" +
							" FROM user_information " +
							" WHERE accountname='"+loginUser.getName()+"'" +
							" AND password='"+loginUser.getPassword()+"'";

		Statement st = ds.getStatement();
		ResultSet rs = st.executeQuery(query);
		rs.next();
		int userId = rs.getInt(1);
		System.out.println(userId);
		ds.close();
		
		return userId;
    }
	
	
	public int getId(String name){
		String query = 	"SELECT id" +
				" FROM user_information " +
				" WHERE accountname='"+name+"'";
		Statement st;
		try {
			st = ds.getStatement();
			ResultSet rs = st.executeQuery(query);
			rs.next();
			return rs.getInt(1);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			ds.close();
		}
		return -1;
		
		
	}
	
	public boolean insert(User createUser){
		boolean correct = execute("INSERT INTO user_information(accountname, password) " +
				"VALUES ('"+createUser.getName()+"','"+createUser.getPassword()+"')");
		return correct;
	}
	
	public boolean remove(User removeUser){
		
		boolean correct = execute("DELETE FROM user_information WHERE accountname='"+removeUser.getName()+"'");
		
		return correct;
	}
	
    /**
     * help function for the execution of sql-queries
     * @param sql
     * @return
     */
    private boolean execute(String sql) {

    	try {
            Statement stmt = ds.getStatement();
            stmt.execute(sql);
            if (stmt != null) {
                stmt.close();
            }
            
            return true;
        } catch (SQLException e) {
        	e.printStackTrace();
            return false;
        } finally {
            ds.close();
        }
    }
}



